Chapter 6: Flow Control
From book Python Programming (Problem solving, Packages and Libraries) published by McGraw Hill Education (India) Private limited.
By:
Note the following:-
>>> symbol and therefore cannot be directly executed. If you want to execute them on IDLE or Jupyter, you need to manually remove the >>> symbol.Markdown and code cells (extension .ipynb) and then downloaded as html. If someone wants to "modify" or "extend' this document, you may ask for the original .ipynb file by sending me an e-mail at:- 999.anuraggupta@gmail.com6.2.1. If…elif…else statement
In Python the “If- - -elif- - - else” statements are used for decision making.
The general form of the ‘if’ statement in Python looks like this:
# ---ON JUPYTER---
if condition_1:# condition_1 must be Bool and evaluate to True or False
statement_block_1
elif condition_2: # condition_2 also must be a bool expression
statement_block_2
else:
statement_block_3
The following script will clarify the concept:
age = input("Enter age: ")
age = int(age) # If a decimal number (Float) entered, it will be truncated
if age >= 19:
print('You are senior')
elif age >= 13:
print('You are a teenager')
else:
print('You are a kid')
print("Exiting")
6.2.2. if…else Statement (Without elif):-
This will be clear from the following example, which checks whether a number is even or odd:
numb = input("Give an integer ")
myN = int(numb)
if (myN % 2 == 0): # % gives remainder. If remainder 0 then even
print(myN, "is even")
else:
print(myN, " is odd")
print("Done")
6.2.3. Omitting the else clause (that is, using an ‘if’ without an ‘else’)
You may omit the ‘else’ clause if you want the user to check a condition and take action based on the result.
For instance, you want to switch on the air conditioner if temperature is above say 25 degrees. If not then do nothing.
numb = input("Give temperature of the room ")
t = float(numb)
if t >25:
print("Switch on the AC")
print("Done")
6.2.4. Nested if... else Statements
It is possible to have if...elif...else statement inside another if...elif...else statement. This is called nesting. Any number of these statements can be nested inside one another. The level of nesting is figured out by indentation.
myAge = input("Enter Age: ")
myAge = int(myAge)
if myAge >= 18:
myComment = 'You can vote'
else:# 3 if-else blocks are nested in this else block
if myAge >= 13:
myComment = 'You are a teenager'
else: # 2 if-else blocks are nested in this else block
if myAge >= 10:
myComment = 'You are in middle school'
else: # 1 if-else block is nested in this else block
if myAge >= 6:
myComment = 'You are in primary school'
else:
myComment = 'You are too small to learn Python'
print ("At age: " + str(myAge) + "->"+ myComment) #This is always executed
Following is yet another example of a program which takes two integer inputs and finds out if they are even or odd:
num1 = input('First number ')
num2 = input('Second number ')
if (int(num1) % 2) == 0: # Modulo operator % gives remainder.
print('First number even')
if (int(num2) % 2) ==0:
print("Second number even")
else:
print('Second number odd')
else: # This else block is entered if first number is odd
print('First number odd')
if (int(num2) % 2) ==0:
print("Second number even")
else:
print('Second number odd')
6.2.5. How to avoid nested if (Good programming technique)
You can use this technique to avoid the ‘nested if-else’ loop in the example of two numbers and testing them for even or odd as follows:
# Input two numbers and test both for even or odd
num1 = int(input('First number '))
num2 = int(input('Second number '))
if ((num1 % 2 == 0) and (num2 % 2 == 0)):
print('Both are even')
elif ((num1 % 2 != 0) and (num2 % 2 == 0)):
print('First odd second even')
elif ((num1 % 2 == 0) and (num2 % 2 != 0)):
print('First even second odd')
else:
print('Both odd')
6.3. while loop
6.3.1. Basics of “while” loop
The syntax of while loop with the optional else is as follows:-
while test_condition: # Loop test_condition must eval to bool True or False
statements # Loop body if test_condition is True
else: # Optional else
statements # executed if test_condition is False
An example of use of ‘while loop’ is as follows:
# The while loop is said to be 'counter-controlled'.
# Here x is acting as a counter
x = 1
print('Number\t'+'Square') # \t is escape for tab
while x <= 10:
print (str(x)+'\t'+str(x**2))#cast x, x**2 to string to concatenate with \t
x = x + 1
print ('done')
# Note \t when kept within quotes is used to generate a tab
Another example:
# Script to successively strip the first 2 characters of a string and print result.
# Note when string s1 becomes empty, ‘while’ s1 will evaluate to False
# and the while loop will terminate
s1 = '112233445566'
while s1:
print(s1)
s1 = s1[2:]
6.3.2. break, continue and pass statements
The pass statement does nothing at all, it is simply a place holder.
The concept of “break” is explained through the following example. The given script takes as input a string, and then prints its characters one by one until it meets the character ‘e’. (Note some of the concepts relate to strings, which is dealt with in the next chapter, so if you don’t follow you can skip this for now and come back after reading strings).
# A script which takes a string and prints its characters one by one
# But which terminates on reaching character 'e'
myStr = input('Input a string ')
x = 0
while x < len(myStr):# index of last character in string is len(myStr)-1
if myStr[x] == 'e':
break # This will cause the while loop to terminate prematurely
print(myStr[x])
x = x+1
The following script explains the concept of “continue”. This script replaces all instances of vowels with a character say hash ie #:-
# A script which replaces vowels with hash ie #
myStr = input('Input a string ')
x = -1 # Need to start from -1 because inside loop you have x = x + 1
newStr = ''
while x < len(myStr)-1:# index of last character in string is len(myStr)-1
x = x + 1
if myStr[x] in ['a', 'e', 'i', 'o', 'u']: #True if x is a vowel
newStr = newStr + '#'
continue # causes jump back to the while statement
newStr = newStr + myStr[x]
print(newStr)
6.3.3. while with else
So far, you have used the “if--else” format. But it is also possible to use the “while--else” format.
The points to be noted regarding the “while -- else” clause are as follows:
while” clause turns false, the “if” block will be executed.while” loop is exited through a “break” statement or if the “while” loop is exited through an “exception”, then the “else” loop will not be executed. One way to think about a “while/ else” is to think of it as an “if/ else with a condition”.
The following code shows an “if/ else with a condition”:
if condition:
# Do something for condition True
else:
# Do something for condition False and proceed with rest of program
An example of an “if/ else” with a condition is:-
# Script to test if a number is even or odd based on if.. else
myStr = input('Give a number-> ')
if int(myStr) % 2 == 0: # if input even, remainder on division by 2 is 0
print(myStr, ' is even')
else:
print(myStr, ' is odd')
So you can replicate the above “if/ else with condition” using a “while/ else with condition”. This is shown as follows:
while condition:
# Do something for condition True
else:
# condition false, handle and proceed with the rest of the program
The following code shows the use of while/ else:
# Script to test if a number is even or odd based on while.. else
myStr = input('Give a number-> ')
while int(myStr) % 2 == 0: # if input even, remainder on division by 2 is 0
print(myStr, ' is even')
break
else:
print(myStr, ' is odd')
6.3.4. Python does not have “do- - until”
Python does not have a “do- - until” type of loop like some programming languages (Like Visual Basic). But this can be simulated using the ‘while’ loop with an ‘if’ statement and a break.
For example:
while True:
#do_something
if bool_exp: # bool_exp is an expression which evaluates to True or False
break
For instance, you can use this format to force the user to give a particular type of input:
while True:
myAge = input('Give your age in years-> ')
if myAge.isdigit(): #If input of digits only then the while loop is exited
print('You are', myAge, ' years old')
break
print('You did not give an integer')
6.3.5. pass statement
A question which often arises is, ‘Why does one need a ‘place holder’ like the “pass” statement?
The answer is that many blocks of code in Python cannot be empty. For instance, if you don’t give an indented block after say an “if” or a “while” or “def” or a “class”, then the interpreter will throw an error.
You cannot use a comment as an indent block.
For instance, the following code will throw an error :-
# This code will give error
x = 5
if x > 0:
# Do something
else:
# Do something else
So you cannot use a “comment as a place holder”.
However, you can write the above code using a “pass” statement as follows:-
# This code is syntactically correct but does nothing
x = 5
if x > 0:
# Do something
pass
else:
# Do something else
pass
6.3.6. Infinite loop
An infinite loop is one which never terminates.
If you create a “while” loop with a boolean expression, which is always True, you will get an infinite loop.
Example:
x =0
while True:
x = x + 1
print(x)
resp = input("press q to quit ")
if resp == 'q':
break
print("end..")
6.4. for loop
6.4.1. Basics of “for” loop
A ‘for’ loop is a definite loop whereas a ‘while’ loop is an indefinite loop.
A ‘while’ loop is an indefinite loop because it simply loops till a condition becomes False. A ‘for’ loop , on the other hand, runs as many times as there are items in the set. The general format of a ‘for’ loop is as follows:
for each_item in mySet: #mySet is some collection of items
#do something
else:
#do something else
Use of simple ‘for’ loop (Without the ‘else’ block) will become clear from the following:
# Loop through each character in a string using for loop
myStr = 'abcd'
for myChar in myStr:
print(myChar)
You can use a ‘for’ loop to step through a list as follows:
# loop through a list of birds
birds = ['crow','hen', 'eagle'] #birds is a list
for bird in birds: # bird is a variable which holds each item in list of birds
print('Bird type-> ',bird)
A for loop to create a string without white spaces
# for loop to create a string without white spaces
# Removes both white spaces and tabs
s1 = input('Give string with white spaces-> ')
s2 = ''# Empty string to which non-space characters of s1 will be added
for x in s1:
if (x != ' ') and (x != '\t'):
s2 = s2 + x
print("Output string is ->", s2)
6.4.2. Nested for loops
Nested for loops are very good for comparing two collections.
For instance, suppose you want to find common characters in two strings. You can do this as follows:
# Nested for loops to compare two string for common characters
s1 = input('First string-> ')
s2 = input("Second string-> ")
for ch1 in s1: # Step through each character is s1
for ch2 in s2: # Step thru each character in s2
if ch1 == ch2:
print(ch1, 'matched')
6.5. range function
6.5. range function
Examples on IDLE
# ---ON IDLE---
>>> list(range(5)) # Will give 0 to 4.
[0, 1, 2, 3, 4]
>>> list(range(2,6)) # Will give 2 to 5
[2, 3, 4, 5]
>>> list(range(0,12,3)) # Will give 0 to 9. (12 is not included)
[0, 3, 6, 9]
>>> list(range(0, -5, -1)) # Will give 0 to -4. (-5 is not included)
[0, -1, -2, -3, -4]
>>> list(range(-2, -12, -2)) # Gives from -2 to -10. (Note -12 not included)
[-2, -4, -6, -8, -10]
>>> list(range(-2, -12, 2)) #Stop less than start & step is positive so empty
[]
>>> list(range(2, 8, -1)) # Since stop > start and step negative so empty
[]
>>>
6.5.2. Using range() function in loop
range() function to generate integers to loop over. You can use the range() function to generate integers to loop over. For instance, you can use the following code to generate all multiples of 3 less than 20:
for counter in range(3,20, 3):
print(counter)
2. Using the range() function to iterate over a sequence like a string or a list
The range() function can be used to iterate over a sequence like a string or a list.
To do so, one must first find the number of characters in the string or number of items in the list and then use this length as a parameter to the range() function as follows:
s1 = 'abcd'
len_s1 = len(s1)
for each_ch in range(len_s1):
print(s1[each_ch])
You can use the range() function to print items in a list also as follows:
myL = ['one', 'two', 'three']
len_myL = len(myL)
for each_itm in range(len_myL):
print(myL[each_itm])
6.5.3. Using “in” operator versus using range() function in “for” loop.
When you are “looping” over a sequence, you may or may not need the “index” of an item.
If you need the individual items in a sequence (but not their index), then you can use the following format for a ‘for’ loop:
for item in mySeq: # mySeq is a sequence like a string or a list
print(item) # prints each item in the sequence
But if you need the index of the individual items in the sequence, then it is better to use the range(len_seq) function, where len_seq is the length of the sequence.
Of course, once you have the index of the individual items of the sequence, then you can always get the item at that index as shown:
mySeq = ['one','two','three']
len_mySeq = len(mySeq)
for idx_item in range(len_mySeq): # len_mySeq gives length of the sequence
# print each index and the item at that index
print('Item at index ',idx_item, 'is ',mySeq[idx_item])
6.7. Iterables
Iteration means going over one at a time. Objects that can be iterated over are called iterables.
This means that if an object in Python is iterable, then to access its various attributes or members, you don’t need to write a ‘while’ loop or a ‘for’ loop or a range function. This is shown for a string as follows:
myS = 'abc'# String is iterable, create a string
for m in myS: # Iterate over a string using for and in
print(m)
In Python, for instance, you can construct a list (that is, create an object of type list) by passing another object to a list constructor as a parameter.
You can, for instance, create a list of characters from a string by passing a string as an object/ argument to a list constructor as shown:-
# ---ON IDLE---
>>> list("Hello World!")
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']